﻿using Common.Communication;
using Common.Device.Enums;
using Common.Device.Interfaces;
using Common.Device.ViewModels;
using Common.Tool.DataTools;
using Common.Tool.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Device.Models
{
    public class CaiJiMoKuai:Device
    {
        /// <summary>
        /// 测试模式
        /// </summary>
        public Enums.CaiJiMoKuaiEnum.TestMode mode { get; set; }
        public string 通道 { get; set; }
        /// <summary>
        /// 生成测试指令
        /// </summary>
        /// <param name="deviceName">仪器名称</param>
        /// <returns></returns>
        public override Order GetOrder(string deviceName)
        {
            //测试指令
            Order order = new Order();
            order.temp = mode.ToString();
            order.name = deviceName;
            switch (通道)
            {
                case "温度":
                    order.range = GetRange("℃");
                    order.deviceModel = JsonConvert.SerializeObject(new { 通道, 上限值, 下限值 });
                    break;
                case "湿度":
                    order.range = GetRange("%RH");
                    order.deviceModel = JsonConvert.SerializeObject(new { 通道, 上限值, 下限值 });
                    break;
                default:
                    break;
            }
            return order;
        }
        /// <summary>
        /// 测试并返回测试结果
        /// </summary>
        /// <param name="dev">仪器实体</param>
        /// <param name="testOrder">测试指令</param>
        /// <returns></returns>
        public override DeviceResult GetResult(object dev, TestOrder testOrder)
        {
            //仪器实体
            var device = dev as ICaiJiMoKuai;
            //测试结果实体
            var result = new DeviceResult();
            Result<double> r1 = new Result<double>();
            //测试模式判断
            switch (mode)
            {
                case CaiJiMoKuaiEnum.TestMode.温湿度:
                    r1 = device.GetValue(通道);
                    //测试结果实体赋值
                    result.success = r1.IsSucceed; if (!result.success)
                    {
                        result.result = r1.Err;
                        break;
                    }
                    result.value = r1.Value;
                    result.unit = 通道 == "湿度" ? "%RH" : "℃";
                    result.result = DataConvert.ToUnit(r1.Value, "F3") + result.unit;
                    break;
                default:
                    break;
            }
            //上下限判断
            if (下限值 != null && result.success)
            {
                result.success = r1.Value >= 下限值;
            }
            if (上限值 != null && result.success)
            {
                result.success = r1.Value <= 上限值;
            }
            return result;
        }
    }
}
